package com.polytech.dao;

import java.util.Date;
import java.util.List;
import java.util.Vector;

import com.polytech.model.Membre;
import com.polytech.model.Topic;
import com.polytech.utils.Database;

public class TopicDaoJdbc implements TopicDao {

	private Database database;
	private MembreDao membreDao;
	public TopicDaoJdbc(Database database,MembreDao membreDao) {
		this.database=database;
		this.membreDao=membreDao;
	}

	@Override
	public void insert(Topic topic) {
		database.insert("Topic",new Object[]{null,
		topic.getSubject(),topic.getText(),topic.getPublicationDate(),topic.getCreator().getLogin()});
		
	}

	@Override
	public Topic select(int id) {
		Topic topic=null;
		Object[][] tab = database.select("Topic",new Object[][]{{"id",id}});
		if(tab!=null){
			topic=new Topic(id,(String)tab[0][1],(String)tab[0][2],(Date)tab[0][3]);
			Membre membre= membreDao.select((String) tab[0][4]);
			topic.setCreator(membre);
		}
		return topic;
	}

	@Override
	public List<Topic> findTheLastThreeTopic() {
		List<Topic>res=null;
		Object[][] tab = database.executeRequete("SELECT * FROM Topic ORDER BY publicationDate");
		if(tab!=null){
			res=new Vector<>();
			for(int i=0;i<3 && i<tab.length;i++){
				System.out.println(tab[i][0].getClass().toString());
				int id=(Integer) tab[i][0];
				Topic topic=select(id);
				res.add(topic);
			}
		}
		return res;
	}

	@Override
	public List<Topic> findAllTopics() {
		List<Topic>res=null;
		Object[][] tab = database.select("Topic",null,new String[]{"id"});
		if(tab!=null){
			res=new Vector<>();
			for(int i=0;i<tab.length;i++){
				System.out.println(tab[i][0].getClass().toString());
				int id=(Integer) tab[i][0];
				Topic topic=select(id);
				res.add(topic);
			}
		}
		return res;
	}
	
	@Override
	public void update(Topic value) {
		// TODO Auto-generated method stub

	}

	@Override
	public void delete(Topic value) {
		// TODO Auto-generated method stub

	}

	public void setDatabase(Database database) {
		this.database = database;
	}

	public void setMembreDao(MembreDao membreDao) {
		this.membreDao = membreDao;
	}

}
